package com.acmedcare.framework.exchange.center.consumer;

import com.acmedcare.framework.exchange.center.core.Const;
import com.acmedcare.framework.exchange.center.core.storage.ConsumerRepository;
import com.acmedcare.framework.exchange.center.entity.bean.Consumer;
import com.acmedcare.framework.exchange.center.entity.dto.ConsumerCommand;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class ConsumerCommandListener {

  final ConsumerProxyContainer proxyContainer;
  final ObjectMapper objectMapper;
  final ConsumerRepository repository;

  public ConsumerCommandListener(
      ConsumerProxyContainer proxyContainer,
      ObjectMapper objectMapper,
      ConsumerRepository repository) {

    this.proxyContainer = proxyContainer;
    this.objectMapper = objectMapper;
    this.repository = repository;
  }

  @SuppressWarnings("unused")
  public void receive(String msg) {

    log.info("接受到消费器指令:"+msg);
    try {

      ConsumerCommand consumerCommand = objectMapper.readValue(msg, ConsumerCommand.class);
      Consumer consumer = consumerCommand.getConsumer();
      if (consumer == null) {

        return;
      }

      if (!System.getenv(Const.GroupName).equals(consumer.getGroupName())) {

        log.info("接受消费器:" + consumer.getName() + "指定环境与当前环境不匹配，消费器指令环境为:" + consumer.getGroupName()
            + ",当前环境为:" + System
            .getenv(Const.GroupName));
        return;
      }

      consumer.setStatus(consumerCommand.getStatus());
      switch (consumerCommand.getStatus()) {

        case UNLOAD:

          proxyContainer.unload(consumer);
          repository.delete(consumer.getConsumerId());
          break;
        case LOADED:

          proxyContainer.load(consumer);
          try {

            repository.delete(consumer.getConsumerId());
            repository.insert(consumer);
          } catch (Exception e) {
            log.warn("插入消费器到调度库中异常,异常信息:" + e.getMessage());
          }
          break;
      }
    } catch (Exception e) {

      log.error("监听消费器任务发生异常：", e);
    }
  }
}
